package com.example.onlinemonitoring.comCenter;

import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Djjyhistory;
import com.example.onlinemonitoring.model.Djjysensor;
import com.example.onlinemonitoring.serviceImpl.DjjysensorServiceImpl;
import com.example.onlinemonitoring.Util.IEEE754Utils;
import lombok.Data;

import org.springframework.context.annotation.Scope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * freemarker填充
 */
@Service("djjyCom")
@Scope("prototype")
public class DjjyCom extends CommPortManager {
    @Autowired
    private DjjysensorServiceImpl djjyserviceimpl;

    public void receiveDatas(String str) {
        str = str.toUpperCase();
        setText(str);
        String addrstr = str.substring(0, 2);
        Integer addrint = parseHex4(addrstr);
        reSend[addrindex] = 0;
        addrindex++;
        String cmdstr = str.substring(2, 4);
        Integer cmdint = parseHex4(cmdstr);
        byte[] carr = HexUtil.hexString2Bytes(str);
        Date dt = new Date();
        Djjysensor djjy = new Djjysensor();
        djjy.setStationid(ad.getStationid());
        djjy.setDevicegroup(ad.getDevicegroup());
        djjy.setDeviceaddr(addrint);
        Djjysensor record = djjyserviceimpl.getModel(djjy);
        djjy.setLastdatatime(dt);
        switch (cmdint) {
            case 3: // freemarker填充
                int startindex = 6;// freemarker填充
                djjy.setLastinsulationresistancevalue(parseHex4(str.substring(startindex, startindex += 4)) * 1.0f);// 绝缘电阻值

                djjy.setLastresistordetection(Integer.parseInt(str.substring(startindex, startindex += 1)));// 在测电阻
                djjy.setLastwaitingfordetection(Integer.parseInt(str.substring(startindex, startindex += 1)));// 待测时间
                djjy.setLastshutdowndelay(Integer.parseInt(str.substring(startindex, startindex += 1)));// 停机延时
                djjy.setLastautomeasurement(Integer.parseInt(str.substring(startindex, startindex += 1)));// 自动测量关闭

                djjy.setLastcurrentvalue(parseHex4(str.substring(startindex, startindex += 4)) * 1.0f);// 电流值
                djjy.setLastvoltagevalue(parseHex4(str.substring(startindex, startindex += 4)) * 1.0f);// 电压值

                djjy.setLastcurrentwarning(Integer.parseInt(str.substring(startindex, startindex += 1)));// 电流预警
                djjy.setLasttimingsignalstatus(Integer.parseInt(str.substring(startindex, startindex += 1)));// 电流报警
                djjy.setLastresistancewarning(Integer.parseInt(str.substring(startindex, startindex += 1)));// 电阻预警
                djjy.setLastresistancealarm(Integer.parseInt(str.substring(startindex, startindex += 1)));// 电阻报警

                djjy.setLastaddress(parseHex4(str.substring(startindex, startindex += 4)) * 1.0f);// 地址

                String alm = "";
                djjy.setLastalarmlevel(0);
                djjy.setLastalarmmessage("");
                if (djjy.getLastcurrentwarning() == 1) {// freemarker填充
                    alm += "电流预警,"; // freemarker填充
                    djjy.setLastalarmlevel(1);
                    djjy.setLastalarmmessage(alm);
                }
                if (djjy.getLasttimingsignalstatus() == 1) {// freemarker填充
                    alm += "电流报警,"; // freemarker填充
                    djjy.setLastalarmlevel(2);
                    djjy.setLastalarmmessage(alm);
                }
                if (djjy.getLastresistancewarning() == 1) {// freemarker填充
                    alm += "电阻预警,"; // freemarker填充
                    djjy.setLastalarmlevel(1);
                    djjy.setLastalarmmessage(alm);
                }
                if (djjy.getLastresistancealarm() == 1) {// freemarker填充
                    alm += "电阻报警,"; // freemarker填充
                    djjy.setLastalarmlevel(2);
                    djjy.setLastalarmmessage(alm);
                }
                if (alm.length() == 0) {
                    GetNormalAlarm("电机绝缘" + record.getDeviceaddr(), record.getDevicegroup(), record.getDeviceaddr(), 0,
                            record.getPointname(),
                            "", false);// freemarker填充
                    setText("无报警");
                } else {
                    GetNormalAlarm("电机绝缘" + record.getDeviceaddr(), record.getDevicegroup(), record.getDeviceaddr(), 0,
                            record.getPointname(),
                            alm, true);// freemarker填充
                    setText(alm);
                }
                djjy.setLastcommunicationstatus(0);
                djjy.setLasthisdatatime(addHistory(djjy));
                setText("设备返回数据： 站点号：1 监测点" + addrint);
                setText("绝缘电阻值" + djjy.getLastinsulationresistancevalue());
                setText("电流值" + djjy.getLastcurrentvalue());
                setText("电压值" + djjy.getLastvoltagevalue());
                setText("地址" + djjy.getLastaddress());
                break;
            default:
                break;
        }
        djjyserviceimpl.Update(djjy, false);
    }

    private Date addHistory(Djjysensor sensor) {
        sensor = djjyserviceimpl.getModel(sensor);
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Djjysensor sensor) {
        Djjyhistory his = new Djjyhistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setDatatime(sensor.getLastdatatime());
        his.setPointname(sensor.getPointname());

        // 需要添加自己定义的属性
        // todo
        his.setInsulationresistancevalue(sensor.getLastinsulationresistancevalue());
        his.setCurrentvalue(sensor.getLastcurrentvalue());
        his.setVoltagevalue(sensor.getLastvoltagevalue());
        his.setAddress(sensor.getLastaddress());
        his.setResistordetection(sensor.getLastresistordetection());
        his.setWaitingfordetection(sensor.getLastwaitingfordetection());
        his.setShutdowndelay(sensor.getLastshutdowndelay());
        his.setAutomeasurement(sensor.getLastautomeasurement());
        his.setCurrentwarning(sensor.getLastcurrentwarning());
        his.setTimingsignalstatus(sensor.getLasttimingsignalstatus());
        his.setResistancewarning(sensor.getLastresistancewarning());
        his.setResistancealarm(sensor.getLastresistancealarm());
        djjyserviceimpl.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        checkType = "crc16";
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        int timeoutsp = (int) Math.round(Appdevice.getTimeoutsp() * 1000);
        timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            rlock.lock();
            try {
                if (isrun) {
                    if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                        addrindex = Appdevice.getAddrmin();
                    cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                    cstr = cstr + CRC16.calcCrc16(cstr);
                    Send(cstr);
                    sendCondition.await(timeoutsp, TimeUnit.MILLISECONDS);
                    if (reSend[addrindex] > 3) {
                        djjyserviceimpl.UpdateStatus(ad, addrindex, 1);
                        reSend[addrindex] = 0;
                        addrindex++;
                    }
                    reSend[addrindex]++;
                } else if (rescode != 0) {
                    setText(resmsg[rescode]);
                }
            } catch (Exception e) {
                // TODO: handle exception
            } finally {
                rlock.unlock();
            }
        }
    }
}